#模拟退火算法
Temperate = 100000 #初始化温度
Tmin=1e-8 # 温度的下界
K = 100 # 迭代的次数

include Math
def f(x)
    return 3*x**5 + 7*x**4 - 40*sin(x)
end

def sy()
    delta = 0.995 # 温度的下降率
    t = Temperate
    minX = 0
    minResult = 999999999
    xArray = []
    for i in 0..K-1
      x = rand * 50 
      xArray.push(x)
    end
    # 迭代的过程
    while(t > Tmin)
      for i in 0..K-1
          # 计算函数结果
        fx = f(xArray[i])
        newX = xArray[i] + (rand() * 2 - 1) * t
        if(newX >=0 && newX <= 50)
            fxNew = f(newX)
            if(fxNew < fx)
               # 替换
               xArray[i] = newX
            else
              # 以概率替换
              p = exp((fxNew - fx) / t)
              if(rand() < p)
                xArray[i] = newX              
              end             
            end
        end
      end
      t = t * delta  
    end
    for i in 0..K-1
        if (f(xArray[i]) < minResult)
          minResult = f(xArray[i])
          minX = xArray[i]
        end
    end
    puts("minX=" + minX.to_s + ",minResult=" + minResult.to_s)
end

sy()